<script setup lang="ts">
import YkPagination from '@yk/components/pagination/YkPagination.vue'
import { Pages } from '@typings/pages'
import { Download, Plus } from '@element-plus/icons-vue'
import YkTableColumn from '@yk/components/table-column/YkTableColumn.vue'
import { ObjectUtil } from '@utils/object-util'
import { ElForm } from 'element-plus'
import { TabBarUtil } from '@/layout/components/tab-bar'
import { TableUtil } from '@utils/table-util'
import { delDeviceAPI, getDeviceListByPageAPI } from '@/api/device'
import { TbDevice } from '@/api/entity/device'
import { useDeviceStatusStore } from '@/dataset/device-status/store'
import { SceneDTO } from '@/api/entity/scene'
import { getSceneListAPI } from '@/api/scene'
import { MountedCheck, toEditPageCheck } from '@/utils'
import { DeviceRoleUtil } from '@/dataset/device-role'
import { unShareDeviceAPI } from '@/api/share'

const router = useRouter()
defineOptions({ name: 'DeviceManage' })

const mc = new MountedCheck()
onMounted(() => {
  DeviceRoleUtil.updateRole()
  searchHandle()
  getSceneList()
  deviceStatusStore.startUpdateStatus()
  mc.end()
})

onActivated(() => {
  if (mc.isMounted()) return
  getTableData()
  DeviceRoleUtil.updateRole()
  deviceStatusStore.startUpdateStatus()
})

onDeactivated(() => {
  deviceStatusStore.stopUpdateStatus()
})

onBeforeUnmount(() => {
  deviceStatusStore.stopUpdateStatus()
})
// region TODO 查询
const searchParams = reactive({
  // 场景id
  groupId: '',
  // 模糊查询
  q: '',
  // 设备状态 0-离线 1-在线
  status: null as boolean
})
function searchHandle () {
  pages.pageNum = 1
  exportParams.value = ObjectUtil.copy(searchParams)
  getTableData()
}
// endregion

// region TODO 表格数据
const pages = reactive(new Pages())
const tableData = shallowRef<TbDevice[]>([])
function getTableData () {
  const loading = ElLoading.service()
  getDeviceListByPageAPI({
    ...pages.getParams(),
    param: searchParams
  }).then((res) => {
    res.result().then((rdata) => {
      tableData.value = rdata.records
      pages.total = rdata.total
    })
  }).finally(loading.close)
}
function delTableItem (id: string) {
  ElMessageBox.confirm('删除当前设备？', '删除提醒').then(() => {
    const loading = ElLoading.service()
    delDeviceAPI({ id }).then((res) => {
      res.result().then(() => {
        getTableData()
      })
    }).finally(loading.close)
  })
}
// endregion

// region TODO 在线状态
const deviceStatusStore = useDeviceStatusStore()
// endregion

// region TODO 场景
const sceneList = shallowRef<SceneDTO[]>()
function getSceneList () {
  getSceneListAPI().then((res) => {
    res.result().then((rdata) => {
      sceneList.value = rdata.data
    })
  })
}
// endregion

// region TODO 导出
const exportParams = shallowRef<typeof searchParams>()
// endregion

// region TODO 添加设备 & 查看 & 编辑
// 前往添加设备
function toAddDevice () {
  router.push({ name: 'AddDevice' })
}
// 前往查看设备
function toCheckDevice (id: string) {
  const _route = TabBarUtil.value.getTagInfo('CheckDevice')
  if (_route && _route.query.id !== id) {
    TabBarUtil.value.close('CheckDevice')
  }
  router.push({ name: 'CheckDevice', query: { id } })
}

// 前往编辑设备
function toEditDevice (id: string) {
  toEditPageCheck({
    id,
    name: 'EditDevice',
    message: '已存在未编辑完成的表单',
    query: { id }
  })
}
// endregion

// region TODO 跳转
function toDeviceData (id: string) {
  router.push({ name: 'DeviceData', query: { id } })
}
// endregion

// region TODO 解绑设备
function unbindDevice (id: string) {
  ElMessageBox.confirm('解绑设备后无法继续查看设备数据，是否继续？', '解绑提醒').then(res => {
    const loading = ElLoading.service()
    unShareDeviceAPI({ id }).then((res) => {
      res.result().then(() => {
        ElMessage.success('设备已解绑')
        getTableData()
      })
    }).finally(loading.close)
  })
}
// endregion

</script>

<template>
  <div class="layout_view d-flex" style="min-height: 100%">
    <div class="c_card-page w-100 flex-1">
      <div class="c_card_header c_card-title bor-divider-b">设备管理</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search mt-3" @submit.prevent="searchHandle">
        <el-form-item label="设备名称：">
          <el-input v-model="searchParams.q" placeholder="请输入设备名称搜索" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchParams.groupId" placeholder="全部场景" filterable clearable>
            <el-option value="">全部</el-option>
            <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchParams.status" placeholder="全部状态" clearable>
            <el-option :value="null">全部</el-option>
            <el-option label="在线" :value="true" />
            <el-option label="离线" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
      </el-form>
      <!--功能栏-->
      <div class="d-flex-between">
        <div class="d-flex">
          <el-button type="primary" :icon="Plus as any" @click="toAddDevice">添加设备</el-button>
        </div>
        <export-file url="/device/export" :params="exportParams">
          <el-button class="c_btn--export" :icon="Download as any">导出</el-button>
        </export-file>
      </div>
      <!--表格-->
      <el-table class="c_table-page w-100 mt-16" stripe :data="tableData">
        <el-table-column label="#" type="index" :index="TableUtil.indexMethod.bind(null, pages)" />
        <el-table-column label="状态" prop="">
          <template #default="scope">
            <el-tag v-if="deviceStatusStore.devicesStatus[scope.row.id]" type="success" effect="dark" size="small">在线</el-tag>
            <el-tag v-else type="info" effect="dark" size="small">离线</el-tag>
          </template>
        </el-table-column>
        <yk-table-column label="设备名称" prop="deviceName" />
        <yk-table-column label="所属场景">
          <template #default="scope">{{ scope.row.groupNameList ? scope.row.groupNameList.join(',') : '/' }}</template>
        </yk-table-column>
        <yk-table-column label="关联网关" prop="gatewayName" />
        <yk-table-column label="关联变量模板" prop="templateName" />
        <yk-table-column label="设备地址" prop="address" />
        <yk-table-column label="备注" prop="notes" />
        <el-table-column label="操作" width="250px">
          <template #default="scope">
            <div class="c_table-operation">
              <el-link type="primary" size="small" @click="toDeviceData(scope.row.id)">设备数据</el-link>
              <el-link type="primary" size="small" @click="toCheckDevice(scope.row.id)">查看</el-link>
              <el-link type="primary" size="small" @click="toEditDevice(scope.row.id)">编辑</el-link>
              <el-link v-if="DeviceRoleUtil.isAdmin(scope.row.id)" type="danger" size="small" @click="delTableItem(scope.row.id)">删除</el-link>
              <el-link v-else type="danger" size="small" @click="unbindDevice(scope.row.id)">解绑</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-affix target=".c_table-page" position="bottom" :offset="0">
        <yk-pagination class="c_table-pagination-page" :pages="pages" @handle="getTableData" />
      </el-affix>
    </div>
  </div>
</template>

<style scoped lang="scss">
</style>
